
"use strict"
function SGoParser()
{
        
}

SGoParser.prototype.decodeSGF=function(sgf)
{
    var index,ch,rb,sb,nodeNumber,node,gametree,start_sgf,begin_sgf,end_sgf;
    
    sb=rb=0;
    nodeNumber=0;
    start_sgf=false;
    begin_sgf=false;
    end_sgf=false;
    gametree=new SGoGameTree();
    for(index=0;index<sgf.length;index++)
    {
        ch=sgf.charAt(index);
        if(ch=='(') 
            start_sgf=true;
        if(start_sgf && (ch==';'))
            begin_sgf=true;
                        
        if(!begin_sgf)
            continue;
        /*    
        if(end_sgf)
            break; 
        */   
        switch (ch)
        {
            case ';' :
                if(sb==0)
                {                                        
                    node=new Node();                    
                    gametree.addNode(node);
                }
                nodeNumber++;
                break;
            case '(' :
            case ')' :
                if(sb!=0)
                    node.m_str+=ch;
                else
                {
                    if(ch=='(')
                    {                        
                        rb++;
                        gametree.pushCurrent();
                    }
                    else
                    {
                        rb--;                     
                        gametree.popCurrent();
                        /*
                        if(rb<0) 
                            end_sgf=true;
                        */
                    }
                }
                break;
            case '[':
            case ']':
                if(ch=='[')
                {
                    sb++;
                    if(sb>1)
                    {
                      node.m_str+="{";
                      sb=1;
                    }
                    else
                       node.m_str+=ch;
                }
                else if(ch==']')
                {
                    if(sb==1)
                        sb--;
                    node.m_str+=ch;
                }
                break;
            case '\\':
                node.m_str+=ch;
                index++;
                ch=sgf.charAt(index);
                if(ch==']')
                   node.m_str+='}';
                break;
            case '\r':
            case '\n':
            case ' ' :
                    if(sb==1)
                        node.m_str+=ch;
                break;
            default:
                node.m_str+=ch;
                break;
        }
    }
    console.log(node.m_str);
    console.log("Parsing sgf done.");
    return gametree;
}


